package com.panshi.repast.Util;

import java.io.ByteArrayOutputStream;
import java.io.File;

import android.graphics.Bitmap;
import android.os.Environment;

import com.panshi.repast.String.AppdataString;

/**
 * 对SD卡，URL的一些操作类
 * 
 * @author huang
 * 
 */
public class Utils {

	/**
	 * 
	 屏幕宽度
	 */
	public static int mScreenWidth = 0;
	/**
	 * 屏幕高度
	 */
	public static int mScreenHeight = 0;

	/**
	 * 
	 * 设置屏幕宽高
	 * 
	 * @param width
	 * @param height
	 */
	public static void setScreenSize(int width, int height) {
		mScreenWidth = width;
		mScreenHeight = height;
	}

	/**
	 * 获取缓存路径
	 * 
	 * @param subFolder
	 *            cache文件路径
	 * @return
	 */
	public static String getCacheDir(String subFolder) {
		String rootDir = null;
		if (isSDCardEnable()) {
			// SD-card available
			rootDir = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + AppdataString.sdcardtemppic + subFolder;

			// 实列化文件
			File file = new File(rootDir);
			if (!file.exists()) // 判断文件存在与否
			{
				file.mkdirs();
			}
		}

		return rootDir;
	}

	/**
	 * 判断是否有SD卡
	 * 
	 * @return
	 */
	public static boolean isSDCardEnable() {
		return android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
	}

	/**
	 * 判断URL地址是否正确
	 * 
	 * @param url
	 * @return
	 */
	public static boolean checkUrl(String url) {
		return url.matches("^[a-zA-z]+://[^\\s]*$");
	}

	/**
	 * 设置编码
	 * 
	 * @param name
	 * @return
	 */
	public static final String encodeBase64(String name) {
		try {
			return Base64.encode(name);
		} catch (Exception e) {
		}
		return name != null ? name : "";
	}

	/**
	 * 截取URL中的字符
	 * 
	 * @param url
	 * @param name
	 * @return
	 */
	public static String getParameter(String url, String name) {
		if (url == null || name == null) {
			return null;
		}

		int start = url.indexOf(name + "=");
		if (start == -1)
			return null;
		int len = start + name.length() + 1;
		int end = url.indexOf("&", len);
		if (end == -1) {
			end = url.length();
		}

		return url.substring(len, end);
	}

	/**
	 * 
	 * 
	 * @param point
	 * @return newpoint
	 */
	public static String formatPoint(String point) {
		try {
			String newpoint = point.replaceAll(",", "");
			java.text.DecimalFormat df = new java.text.DecimalFormat(
					"##,###,###");
			return df.format(Double.parseDouble(newpoint));
		} catch (Exception e) {
			return point;
		}
	}

	/**
	 * 将Bitmap转换为byte
	 * 
	 * @param bm
	 * @return
	 */
	public static byte[] bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

}